import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';

extension Toast on String {
  void toast() {
    BotToast.showText(
      text: this,
      contentColor: Colors.white,
      textStyle: TextStyle(
        fontSize: 14.sp,
        fontWeight: FontWeight.w400,
        color: Colors.black,
      ),
      borderRadius: BorderRadius.all(Radius.circular(8.w)),
      contentPadding: EdgeInsets.symmetric(vertical: 12.w, horizontal: 18.w),
      align: Alignment.center,
    );
  }
}

/// 其他扩展
extension StringExt on String {
  /// 打开链接
  Future<bool> openUrl() async {
    final url = Uri.parse(this);
    if (!(await canLaunchUrl(url))) {
      return false;
    }
    if (!(await launchUrl(url))) {
      print('Could not launch $url');
      return false;
    }
    return true;
  }
}

extension StringSpace on String {
  bool get isAllSpaces => RegExp(r'^\s*$').hasMatch(this);

  /// 首字母大小
  String capitalize() {
    return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
  }
}

extension StringJson on String {
  /// 判断是否是json字符串
  bool isValidJsonMap() {
    try {
      final parsed = json.decode(this);
      return parsed is Map<String, dynamic>;
    } catch (e) {
      return false;
    }
  }
}

extension NullableStringExtension on String? {
  String orDefault([String defaultValue = '']) {
    return this ?? defaultValue;
  }
}
